package com.payment.timingtask;

import com.payment.config.dto.StringOutputConstant;
import com.payment.service.alast.impl.AfterPayDeal;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;

/**
 * @author lm
 * @date 2020/9/19 9:15
 */
@Component
@EnableScheduling
@Api(value = "支付完成之后轮循的定时任务")
public class AfterPayDealTask {
    private static Logger logger = Logger.getLogger(AfterPayDealTask.class);
    private static final String UN_RE_ORDER = "un_re_order:";
    @Value("${system.autoTask}")
    private boolean autoTask;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    AfterPayDeal afterPayDeal;

    @Scheduled(cron = "0 0/1 * * * ?")
    @Async
    public void execute() {
        if (autoTask) {
            task();
        }
    }

    public void task() {
        //去redis把需要轮循的数据拿出来：
        Set set = redisTemplate.keys(UN_RE_ORDER + "*");
        if (null == set || set.isEmpty()) {
            return;
        }
        //往下走就是说明redis里面是有值的
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            //先判断一下取到的值有没有效
            if (StringUtils.isBlank(key) || StringUtils.isBlank((String) redisTemplate.opsForValue().get(key))) {
                logger.info("取到的值有问题");
                return;
            }
            //把redis的里面存着的某个key对应的值取出来
            String payId = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isBlank(payId)) {
                logger.info("给payId赋值有问题");
                return;
            }
            //新起一个方法去调订购套餐接口，然后根据订购套餐的结果判断要不要把这个key删掉
            if (StringOutputConstant.CODE_SUCCESS.equals(afterPayDeal.deal(payId))) {
                redisTemplate.delete(key);
                logger.info(key + ":删除成功");
            }
        }

    }


}
